import dayjs from 'dayjs';

interface RequestLog {
  type: 'request' | 'response';
  url: string;
  method?: string;
  params?: any;
  status?: number;
  data?: any;
  duration?: number;
  timestamp: number;
}

class Logger {
  private static instance: Logger;
  private readonly MAX_LOGS = 1000; // 最大日志数量
  private readonly STORAGE_KEY = '__APP_REQUEST_LOGS__';

  private constructor() {}

  static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }

  // 保存日志
  async saveLog(log: RequestLog): Promise<void> {
    try {
      const logs = await this.getLogs();
      logs.unshift(log);
      
      // 限制日志数量
      if (logs.length > this.MAX_LOGS) {
        logs.length = this.MAX_LOGS;
      }

      uni.setStorageSync(this.STORAGE_KEY, logs);
    } catch (error) {
      console.error('保存日志失败:', error);
    }
  }

  // 更新某条日志
  async updateLog(log: RequestLog): Promise<void> {
    try {
      const logs = await this.getLogs();
      const index = logs.findIndex(l => l.id === log.id);
      if (index !== -1) {
        logs[index] = log;
        uni.setStorageSync(this.STORAGE_KEY, logs);
      }
    } catch (error) {

    }
  }
  // 获取所有日志
  async getLogs(): Promise<RequestLog[]> {
    try {
      const logs = uni.getStorageSync(this.STORAGE_KEY);
      return logs || [];
    } catch (error) {
      console.error('获取日志失败:', error);
      return [];
    }
  }

  // 清除所有日志
  async clearLogs(): Promise<void> {
    try {
      uni.removeStorageSync(this.STORAGE_KEY);
    } catch (error) {
      console.error('清除日志失败:', error);
    }
  }

  // 格式化日志时间
  formatLogTime(timestamp: number): string {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
  }
}

export const logger = Logger.getInstance();